from front.models import Quizzes, Questionnaire, User  # 导入数据库模型
from django.http import JsonResponse as JR
from django.views.generic.base import View
from .models import PlatformLog, Doctor
from django.shortcuts import render
from UPI import settings
import hashlib
import time
import json


# 重写JsonResponse对象，默认返回中文和内容可为列表
class JsonResponse(JR):
    def __init__(self, data, safe=False, json_dumps_params={'ensure_ascii': False}, **kwargs):
        super(JsonResponse, self).__init__(data, safe=safe, json_dumps_params=json_dumps_params)


# 登陆视图
class LoginView(View):
    def get(self, res):
        return render(res, 'cms/login.html')

    def post(self, res):
        name = res.POST.get('name')  # 管理员名称
        pwd = res.POST.get('pwd')  # 管理员密码
        if name == settings.USERNAME:  # 判断名称
            if pwd == settings.PASSWORD:  # 判断密码
                s = res.META['REMOTE_ADDR'] + str(time.time())  # 访问IP+时间戳
                settings.SECRET_KEY = hashlib.md5(s.encode(encoding='UTF-8')).hexdigest()  # md5加密生成SECRET_KEY
                return JsonResponse({'state': True, 'secret_key': settings.SECRET_KEY})  # 返回密钥给前端
            else:
                return JsonResponse({'state': False, 'msg': '密码错误'})
        else:
            return JsonResponse({'state': False, 'msg': '用户名错误'})


# 后台首页视图
class IndexView(View):
    def get(self, res):
        context = {
            "date": [],
            "register": [],
            "visit": [],
            "test": [],
            "advisory": [],
            "register_count": 0,
            "visit_count": 0,
            "test_count": 0,
            "advisory_count": 0
        }
        for i in PlatformLog.objects.all():  # 从数据库中提取平台记录数据
            context['date'].append(i.date)
            context['register'].append(i.log['register'])
            context['visit'].append(i.log['visit'])
            context['test'].append(i.log['test'])
            context['advisory'].append(i.log['advisory'])
            context['register_count'] += i.log['register']
            context['visit_count'] += i.log['visit']
            context['test_count'] += i.log['test']
            context['advisory_count'] += i.log['advisory']
        return render(res, 'cms/index.html', context=context)  # 返回后台首页


# 用户管理视图
class UserControlView(View):
    def get(self, res):
        return render(res, 'cms/user_control.html')

    def post(self, res):
        action = res.POST.get('action')  # 行为关键字
        uid = res.POST.get('uid')  # 用户ID
        if action == 'del':  # 删除用户
            try:
                User.objects.get(id=uid).delete()  # 删除数据库中的用户数据
            except:
                return JsonResponse({'state': False})
        elif action == 'alter':  # 修改用户
            form = json.loads(res.POST.get('form'))  # 获取表单数据
            user = User.objects.get(id=form['id'])  # 从数据库中提取用户数据
            # 修改具体数据
            user.name = form['name']
            user.pwd = form['pwd']
            user.email = form['email']
            user.age = form['age']
            user.sex = form['sex']
            user.save()  # 保存

        # 返回所有用户数据
        users = []
        for i in User.objects.all():
            users.append({
                "id": i.id,
                "name": i.name,
                "pwd": i.pwd,
                "email": i.email,
                "sex": i.sex,
                "age": i.age,
                "last_login": i.last_login,
                "data": [i for i in i.data.values()]
            })
        return JsonResponse({'state': True, 'users': users})


# 心理咨询管理
class AdvisoryView(View):
    def get(self, res):
        return render(res, 'cms/advisory.html')

    def post(self, res):
        action = res.POST.get('action')  # 行为关键字
        uid = res.POST.get('uid')  # 用户ID
        if action == 'del':  # 删除用户
            try:
                Doctor.objects.get(id=uid).delete()
            except:
                return JsonResponse({'state': False})
        elif action == 'alter':  # 修改医生数据
            form = json.loads(res.POST.get('form'))  # 获取表单数据
            try:
                # 修改数据库中医生的数据
                Doctor.objects.filter(id=form['id']).update(name=form['name'], office=form['office'],
                                                            level=form['level'], hospital=form['hospital'],
                                                            serve=form['serve'], score=form['score'],
                                                            intro=form['intro'])
            except:
                return JsonResponse({'state': False})
        elif action == 'add':  # 添加医生
            form = json.loads(res.POST.get('form'))  # 获取表单数据
            # 向数据库中添加医生
            Doctor.objects.create(name=form['name'], office=form['office'],
                                  level=form['level'], hospital=form['hospital'],
                                  serve=form['serve'], score=form['score'],
                                  intro=form['intro'])
        elif action == 'head':  # 医生头像
            try:
                file = res.FILES.get('file')  # 获取文件对象
                uid = res.POST.get('uid')  # 医生ID
                file_path = f'/static/images/{int(time.time() * 10)}.jpg'  # 存储路径
                with open(str(settings.BASE_DIR) + file_path, 'wb') as fp:  # 保存文件
                    fp.write(file.read())
                Doctor.objects.filter(id=uid).update(picture=file_path)  # 更新医生数据
            except:
                return JsonResponse({'state': False})
        # 返回所有医生数据
        doctor = []
        for i in Doctor.objects.all():
            doctor.append({
                "id": i.id,
                "name": i.name,
                "picture": i.picture,
                "office": i.office,
                "level": i.level,
                "hospital": i.hospital,
                "serve": i.serve,
                "score": i.score,
                "intro": i.intro,
                "task": i.task
            })
        return JsonResponse({'state': True, 'doctor': doctor})
